#include "verificationcodebutton.h"
#include<QTime>
#include<QTextFormat>
VerificationCodeButton::VerificationCodeButton(QWidget *parent)
    :QPushButton(parent)
    ,currentSeconds(0)
    ,countdownSeconds(60)
   {
        timer=new QTimer(this);
        originstring=text();
        connect(timer,&QTimer::timeout,this,&VerificationCodeButton::updateCountdown);
        //connect(this, &VerificationCodeButton::clicked, this, &VerificationCodeButton::onButtonClicked);

    }

VerificationCodeButton::~VerificationCodeButton(){
    if(timer->isActive()){
        timer->stop();
    }
}

void VerificationCodeButton::updateCountdown(){
    currentSeconds--;
    if(currentSeconds<=0){
        stopCountdown();
    }
    else{

        setText(QString("%1s").arg(currentSeconds));

    }
}

void VerificationCodeButton::stopCountdown(){
    timer->stop();
    setEnabled(true);
    if(originstring.isEmpty()){
        originstring="获取";
    }
    setText(originstring);
}
void VerificationCodeButton::startCountdown(int seconds=60){
    if(seconds<=0){
        return ;
    }
    setEnabled(false);

    currentSeconds=seconds;
    countdownSeconds=currentSeconds;
    timer->start(1000);

    updateCountdown();
}
// 新增槽函数
void VerificationCodeButton::onButtonClicked()
{
    // 点击时开始倒计时
    startCountdown(countdownSeconds);
}
